package com.dmw.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dmw.reggie.common.R;
import com.dmw.reggie.entity.Category;
import com.dmw.reggie.service.CategoryService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("category")
public class CategoryController {

    @Resource
    private CategoryService categoryService;


    /**
     * 分压查询菜品和套餐分类
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public R<Page<Category>> page(Long page, Long pageSize){
        // 构造分页构造器
        Page<Category> pageInfo = new Page<>(page, pageSize);

        // 构造条件构造器
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(Category::getSort);

        // 分页查询
        categoryService.page(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }


    /**
     * 新增菜品或者套餐
     * @param category
     * @return
     */
    @PostMapping
    public R save(@RequestBody Category category){
        // 新增（使用了统一异常处理对下面操作出现异常进行处理）
        categoryService.save(category);
        return R.success(null);
    }

    /**
     * 修改分类内容
     * @param category
     * @return
     */
    @PutMapping
    public R update(@RequestBody Category category){
        categoryService.updateById(category);
        return R.success(null);
    }

    /**
     * 根据 id 删除对应的分类
     * @param ids
     * @return
     */
    @DeleteMapping
    public R delete(Long ids){

        categoryService.removeById(ids);

        return R.success(null);
    }

    /**
     * 根据 type 获取分类数据
     * @param category
     * @return
     */
    @GetMapping("/list")
    public R<List<Category>> list(Category category){
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType())
                .orderByAsc(Category::getSort)
                .orderByDesc(Category::getUpdateTime);
        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }
}
